//2014-02-27
var previewQuestionModel;
//self.questionPreview						= ko.observable(new PreviewQuestionModel())//ADDED BY Vikash Bhardwaj For Preview

var swfDimensionVOArr = new Array();

var SwfDimensionVO = function(dataStr) {
	var arr = dataStr.split(",");
	this.height = ko.observable(data.height || "");
	this.width = ko.observable(data.width || "");
	this.url = ko.observable(data.url || "");
};

function sendToJavaScript(value) {
	//console.log("2014-02-10 2 d w sendToJavaScript value :: ", value);
	var myindex = value.indexOf("dimensionStr:");
	if (myindex == 0) {
		//console.log("2014-02-10 2 d w sendToJavaScript value :: ", value);
		//console.log("2014-02-10 2 d sendToJavaScript :: 124 pushed vlaue :: ", value);
		swfDimensionVOArr.push(value);

		$("embed").each(function(index, tempValue) {

			if ($(this).attr('name') != "wrapperContent1") {

				//console.log("sendToJavaScript :: 124 index :: ", index);
				//console.log('sendToJavaScript :: each :', $(this).attr('src'));
				//console.log('sendToJavaScript :: each this ', this, ':', $(this).attr('width'));
				var fullImagePath = $(this).attr('src');

				//console.log("sendToJavaScript :: 124 fullImagePath :: ", fullImagePath);
				//console.log("sendToJavaScript :: 124 value :: ", value);
				var myCurrentIndex = value.indexOf(fullImagePath);
				//console.log("sendToJavaScript :: 124 myCurrentIndex :: ", myCurrentIndex);
				if (myCurrentIndex > 0) {
					//console.log("xxxxxxxx sendToJavaScript :: 124 1 value == fullImagePath :: ", fullImagePath);
					//console.log("test 1 sendToJavaScript :: value :: ", value);
					var widthStr = value.split(",")[2];
					var heightStr = value.split(",")[3];

					//console.log("sendToJavaScript :: $(this):: ", $(this));
					//console.log("sendToJavaScript :: this:: ", this);
					var singleQuestionViewSelector = $(this).closest('#singleQuestionViewID');

					//console.log("sendToJavaScript :: singleQuestionViewSelector :: ", singleQuestionViewSelector);
					/**
					 * If it is a preview then there will be original height
					 * else 500;
					 */
					var isActualQuestionPreview = singleQuestionViewSelector.length;
					//console.log("sendToJavaScript :: isActualQuestionPreview :: ", isActualQuestionPreview);
					if (isActualQuestionPreview) {
						//console.log("if sendToJavaScript :: isActualQuestionPreview  :: 500 ");

					} else {
						//TODO: get the closest TD width and set it.
						//console.log("else  sendToJavaScript :: isActualQuestionPreview  :: 500 ");
						if (Number(widthStr) > 500) {
							//console.log("sendToJavaScript :: Number(widthStr) > 500 :: ");
							widthStr = "500";
						};
					}
					//console.log("sendToJavaScript :: $(this).attr('src') ", $(this).attr('src'));
					//console.log("2014-02-10 2 d w sendToJavaScript :: 124 1 widthStr,heightStr :: ", widthStr, heightStr);
					$(this).attr("width", widthStr);
					$(this).attr("height", heightStr);
					//console.log("2014-02-10 2 d w test 1 output object element $(this):: ", $(this));
					//console.log("xxxxxxxx sendToJavaScript :: 124 value == fullImagePath :: ", fullImagePath);
					//console.log("sendToJavaScript :: 124 1 $(this).attr('width'), $(this).attr('height') :: ", $(this).attr('width'), $(this).attr('height'));

				};

			};

		});

	};

	//console.log("swfDimensionVOArr :: ", swfDimensionVOArr);
	var output = document.getElementById("output");
	output.value += "ActionScript says: " + value + "\n";

}

/**
 * Preview QuestionModel
 * same as RadioVO in "qpaper_preview js"
 * TODO:store swf class path
 */
function PreviewQuestionModel() {

	var self = this;
	self.name = ko.observable("PreviewQuestionModel");
	self.questionData = ko.observable();
	self.isVisibleDialog = ko.observable();

	self.questionId = ko.observable();
	self.myCEimageUrl = ko.observable("");
	self.isFromCE = ko.observable(0);

	self.QP_PreviewMode = ko.observable(QP_MODE_SINGLE_QUESTION);

	self.closePreview = function(XML) {
		self.isVisibleDialog(false);
	};

	self.openPopup = function(details, myQuestionId) {

		//console.log("2014-02-10 openPopup myQuestionId :: ", myQuestionId);
		self.isVisibleDialog(true);
		if (details) {
			/**
			 *TODO: Remove "qbank" keep "teqb"
			 */
			if (myQuestionId.indexOf("qbank") != -1 || myQuestionId.indexOf("teqb") != -1) {
				//console.log("2014-02-10 is from TE :: ");
				// is from TE
				self.isFromCE(0);
			} else {
				//is from CE
				//console.log("2014-02-10 is from CE :: ");
				self.isFromCE(1);
			};
		};

		self.updateMe = function(myCEimageUrl) {
			//console.log("2014-02-10 myCEimageUrl :: ", myCEimageUrl);
			//console.log("2014-02-10 details :: ", details);
			if (!myCEimageUrl) {
				myCEimageUrl = "";
			};
			self.myCEimageUrl(myCEimageUrl);

			if (details) {
				var myTemplate_Type = TEMPLATE_TYPE_SINGLECHOICE;
				if (self.isFromCE()) {
					myTemplate_Type = $.parseXML(details).childNodes[0].getAttribute('type');

					self.questionData(new RadioVO(details, myQuestionId, 1, myCEimageUrl));
				} else {
					myTemplate_Type = $(details).attr("template_Type");
					/**
					 *Set the  TEMPLATE_TYPE to SINGLECHOICE if not there
					 * TODO:
					 */
					//console.log("before 2014-02-10 myTemplate_Type :: ", myTemplate_Type);
					if (!myTemplate_Type) {
						myTemplate_Type = TEMPLATE_TYPE_SINGLECHOICE;
					};
					//console.log("after 2014-02-10 myTemplate_Type :: ", myTemplate_Type);
					if (myTemplate_Type == TEMPLATE_TYPE_FILLUP) {
						self.questionData(new FillUpVO(details, myQuestionId, 0));
					};
					if (myTemplate_Type == TEMPLATE_TYPE_OPENENDED_STEMONLY || myTemplate_Type == TEMPLATE_TYPE_OPENENDED_STEMIMAGE) {
						self.questionData(new OpenEndedVO(details, myQuestionId, 0));
					};
					//Radio VO will work here
					if (myTemplate_Type == TEMPLATE_TYPE_TRUEFALSE || myTemplate_Type == TEMPLATE_TYPE_SINGLECHOICE || myTemplate_Type == TEMPLATE_TYPE_MULTIPLECHOICE) {
						self.questionData(new RadioVO(details, myQuestionId, 0, myCEimageUrl));
					};
				};

			} else {
				//console.log("2014-02-10 self.qStem :: " + self.qStem() + "  << #######.details :: ", details);
			};
		};
		//console.log("self.isFromCE() :: ", self.isFromCE());
		if (self.isFromCE()) {
			getImagePathClassEdgeUrl(myQuestionId, self, true);
		} else {
			//console.log("came here in else :: ");
			self.updateMe("");
		}

		//initSVGui();

	};

	self.getQuestionBankData = function(myQPUrl, _questionId, showPreview) {
		var fullUrl = myQPUrl + "getQuestionBankData" + "&questionId=" + _questionId;
		console.log("networkCall : getQuestionBankData : getJSON:: questionBankPreview js");
		var myData;
		//console.log("getQuestionBankData fullUrl :: ", fullUrl);
		var jqxhr = $.getJSON(fullUrl, {
			returnformat : 'json'
		}, function(allData) {
			//console.log("allData :: ", allData);
			myData = allData;
		});

		/** ----------------------------------------- Event Listeners */
		jqxhr.done(function(allData) {
			/* Working the Object Access */
		});
		jqxhr.fail(function() {
			//console.log("2014-02-10 error getQuestionBankData fullUrl :: ", fullUrl);
		});
		jqxhr.always(function() {
		});
		jqxhr.complete(function(ddd) {
			//console.log("2014-02-10 complete getQuestionBankData fullUrl myData :: ");
			if (showPreview) {
				//console.log("2014-02-10 showPreview :: ", showPreview);
				self.openPopup(myData, _questionId);
			};
		});
		/** ----------------------------------------- End Event Listeners */
	};
};
function getSwfDimensionCE(fullImagePath) {
	var dimensionResultStr = "";
	//console.log("2014-02-10 2 d getSwfDimensionCE :: fullImagePath :: ", fullImagePath);
	for (var i = 0; i < swfDimensionVOArr.length; i++) {
		var dimensionStr = swfDimensionVOArr[i];
		//console.log("2014-02-10 2 d dimensionStr :: ", dimensionStr);
		var myindex = dimensionStr.indexOf(fullImagePath);
		//console.log("getSwfDimensionCE indexOf(fullImagePath) myindex :: ", myindex);
		if (myindex > 0) {
			dimensionResultStr = dimensionStr;
			//console.log("2014-02-10 2 d dimensionResultStr inner:: ", dimensionResultStr);
			break;
		};
	};

	return dimensionResultStr;
};

function getImagePathClassEdgeUrl(questionId, questionVO, isFromCE) {
	var imagePathClassEdgeUrl = $('#qPathLoadUrl').val();
	//console.log("2014-02-10 qb :: getImagePathClassEdgeUrl >> imagePathClassEdgeUrl :: ", imagePathClassEdgeUrl);
	//console.log("2014-02-10 qb :: getImagePathClassEdgeUrl >> questionId :: ", questionId);
	console.log("networkCall : getImagePathClassEdgeUrl :: questionBankPreview js");
	$.ajax({
		url : imagePathClassEdgeUrl,
		type : "post",
		data : {
			id : questionId,
			type : 'question'
		},
		success : function(result) {
			//console.log("2014-02-10 qb getImagePathClassEdgeUrl >>> result, questionId :: ", result, questionId);
			if (isFromCE) {
				result = result + '/internal/quiz/';
			} else {
				result = '';
			};
			//console.log("2014-02-10 qb questionVO, result :: ", questionVO, result);
			questionVO.updateMe(result, questionVO);
		},
		error : function(jqXHR, textStatus, errorThrown) {
			//console.log("2014-02-10 qb getImagePathClassEdgeUrl >>>fail>> questionId :: ", imagePathClassEdgeUrl, questionId);
		}
	});
};
//console.log("2014-02-10 imgLoadUrl 112:: ", imgLoadUrl);
/**
 * 	<b>stringHTML:</b> text with all image tags also<br>
 *  <b>questionId:</b> question Id <br>
 * 	<b>isSave:</b> only true for Vikash question Creation <br>
 * 	<b>myCEimageUrl:</b> that is got for CE from server<br>
 * 	<b>isQPSubQuestionInfoVOQstem :</b> if it is in the list of Question Dispaly then need to short the Image Size to fit the Width.<br>
 */
function getHtmlText(stringHTML, questionId, isSave, myCEimageUrl, isQPSubQuestionInfoVOQstem) {
	//console.log("getHtmlText 2014-02-10 imgLoadUrl 112222222:: ", imgLoadUrl);
	//console.log("inout ==============================================================================================");
	//console.log("inout input stringHTML :: ", stringHTML);
	var imageBaseUrl = $('#imgLoadUrl').val();
	if (!imageBaseUrl) {
		if (imgLoadUrl) {
			imageBaseUrl = imgLoadUrl;
		};
	};

	var is_QPSubQuestionInfoVO_Qstem = isQPSubQuestionInfoVOQstem;
	//console.log("getHtmlText :: 11 pre 111 is_QPSubQuestionInfoVO_Qstem :: ", is_QPSubQuestionInfoVO_Qstem);
	//  /delegate/fileservice/

	//  http://p1392:8080/group/classedge/flex-service?p_p_id=FlexServiceManagement_WAR_ceportaladmin&p_p_lifecycle=0&p_p_state=exclusive&p_p_col_id=column-1&p_p_col_count=1&_FlexServiceManagement_WAR_ceportaladmin_Operation=getInternalImagePath&questionId=199ADBE5-3F8E-4C7A-AC01-75FBED3506F6&type=question&fileName=internal/quiz/qz_12accen_66_img04.swf&id=88DE9FD2-4275-4C6B-8DA1-4827D990E37A
	/**
	 Correct one to fire for getting the image path CE
	 http://p1392:8080/group/classedge/flex-service?p_p_id=FlexServiceManagement_WAR_ceportaladmin&p_p_lifecycle=0&p_p_state=exclusive&p_p_col_id=column-1&p_p_col_count=1&_FlexServiceManagement_WAR_ceportaladmin_Operation=getInternalImagePath&questionId=199ADBE5-3F8E-4C7A-AC01-75FBED3506F6&type=question&id=88DE9FD2-4275-4C6B-8DA1-4827D990E37A

	 // working file path

	 http://p1392:8080/delegate/fileservice/tp/tata/6/accountancy/tp-2a1fc3fc-17ab-43cd-9a62-666a2a0cd856/internal/quiz/qz_12accen_66_img04.swf

	 Formulla: imageBaseUrl + myCEimageUrl + 'internal/quiz/' + fileNamePart

	 */

	//console.log("imageBaseUrl :: ", imageBaseUrl);
	//for local
	if (!jQuery('#imgLoadUrl').val()) {
		//imageBaseUrl = "/delegate/fileservice/";
		//console.log("local getHtmlText :: imageBaseUrl :: ", imageBaseUrl);
	} else {
		//console.log("server getHtmlText :: imageBaseUrl :: ", imageBaseUrl);
	};

	var fullImagePath;

	x = document.createElement("ppp");

	var att = document.createAttribute("isQstem");
	att.value = is_QPSubQuestionInfoVO_Qstem;
	x.setAttributeNode(att);
	//console.log("stringHTML :: ",stringHTML);
	x.innerHTML = stringHTML;
	var allNodes = x.getElementsByTagName("*");
	var len = allNodes.length;

	for (var i = 0; i < len; i++) {

		var imgNode = allNodes[i];
		//console.log("imgNode.nodeName :: ",imgNode.nodeName);
		if (imgNode.nodeName == "IMG" && imgNode.getAttribute("src")) {

		} else {
			continue;
		}
		//BO create the image file name
		var fileNamePart = imgNode.getAttribute('src');
		//console.log(" before fileNamePart :: ", fileNamePart);
		//For Save : called by Vikash only from QBank
		//from Class Edge

		if (fileNamePart.indexOf(imageBaseUrl) != -1) {
			//if there is a base url present at the time of save then Remove it.
			fileNamePart = fileNamePart.replace(imageBaseUrl, "");
			//console.log("if has path already: fileNamePart :: ", fileNamePart);
		};
		//console.log("fileNamePart.indexOf(imageBaseUrl) :: ", fileNamePart.indexOf(imageBaseUrl));
		//from Test Edge
		//console.log("2014-02-27 isSave :: ", isSave);
		if (isSave) {
			fullImagePath = fileNamePart;
		} else {
			if (myCEimageUrl == undefined) {
				fullImagePath = imageBaseUrl + fileNamePart;
			} else {
				fullImagePath = imageBaseUrl + myCEimageUrl + fileNamePart;
			}
			//console.log("else normal: fileNamePart :: ", fileNamePart);
		};
		/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

		//console.log("fileNamePart :: fullImagePath ", fullImagePath, ">>", imageBaseUrl, "###", myCEimageUrl, "---", fileNamePart);
		//EO create the image file name

		//console.log("2014-02-27 imageBaseUrl :: ", imageBaseUrl);
		//console.log("2014-02-27 fullImagePath :: ", fullImagePath);
		imgNode.setAttribute('src', fullImagePath);

		// BO replace the <img tag with embed tag
		//console.log("getHtmlText :: 11 pre is_QPSubQuestionInfoVO_Qstem :: ", is_QPSubQuestionInfoVO_Qstem);
		/**
		 *check for if it is a swf then only proceed for replacing the tag
		 *type="swf"
		 *
		 * TODO: Check for Extension and Replace
		 */
		if (fileNamePart.indexOf('.swf', fileNamePart.length - 5) != -1 || fileNamePart.indexOf('.class', fileNamePart.length - 7) != -1) {
			//is flash
			//console.log("file type is flash fileNamePart :: ", fileNamePart);
			imgNode.removeAttribute('type');
			var outerHtmlStr = $(imgNode)[0].outerHTML;
			var dimensionResultStr = getSwfDimensionCE(fullImagePath);
			//console.log("2014-02-10 2 d dimensionResultStr :: ", dimensionResultStr);
			/**
			 *Send to as to load the swf and get the Dimension.
			 *
			 * TODO: Storage Process
			 */
			var res = "";
			var maxImageSizeStr = "";
			//console.log("2014-02-10 2 getHtmlText :: 11 is_QPSubQuestionInfoVO_Qstem :: ", is_QPSubQuestionInfoVO_Qstem);

			if (dimensionResultStr) {
				//console.log("2014-02-10 2 d not sendToActionScript called :: dimensionResultStr :: ", dimensionResultStr);
				var widthStr = dimensionResultStr.split(",")[2];
				var heightStr = dimensionResultStr.split(",")[3];
				//console.log("2014-02-10 2 d getHtmlText :: 11 widthStr, heightStr :: ", widthStr, heightStr);
				//console.log("is_QPSubQuestionInfoVO_Qstem :: ", is_QPSubQuestionInfoVO_Qstem);
				if (is_QPSubQuestionInfoVO_Qstem) {
					/**
					 *TODO: get the closest TD width and set it.
					 */
					widthStr = '500';

				}

				//console.log("2014-02-10 2 d widthStr :: questionBankPreview js", widthStr);

				res = '<object width="100%" height="100%"><embed ' + maxImageSizeStr + ' src="' + fullImagePath + '" quality="high" type="application/x-shockwave-flash" width="' + widthStr + '" height="' + heightStr + '" scale="default" allowScriptAccess="always"></object>';
			} else {
				//console.log("2014-02-10 2 d sendToActionScript called :: fullImagePath :: ", fullImagePath);
				sendToActionScript(fullImagePath, 'getHtmlText');
				res = '<object width="100%" height="100%"><embed ' + maxImageSizeStr + ' src="' + fullImagePath + '" quality="high" type="application/x-shockwave-flash" width="100" height="100" scale="default" allowScriptAccess="always"></object>';
			};
			//console.log("2014-02-10 2  $(imgNode)[0].outerHTML :: ", $(imgNode)[0].outerHTML);
			$(imgNode)[0].outerHTML = res;

			//console.log("2014-02-10 2 d output object element getHtmlText :: 11 res :: ", res);
			//console.log("output object element imgNode :: ",imgNode);
			/**/
			//$( imgNode ).append( res );
		} else {
			//not flash
			//console.log("file type is image fileNamePart :: ", fileNamePart);
		};
	};

	// BO replace the imgtag with embed tag
	var result = x.innerHTML;
	var newGT_stripped_Html = result.replace("&gt;", ">");
	newGT_stripped_Html = newGT_stripped_Html.replace("<!--[CDATA[", "");
	newGT_stripped_Html = newGT_stripped_Html.replace("]]-->", "");
	newGT_stripped_Html = newGT_stripped_Html.replace("]]>", "");

	//console.log("inout output newGT_stripped_Html html:: ", newGT_stripped_Html);
	return newGT_stripped_Html;
}

function CDATATrim(textStr) {
	var newStr = String(textStr).replace("<!--[CDATA[", "").replace("]]-->", "");
	newStr = String(newStr).replace("]]>", "");
	newStr = String(newStr).replace("]]&gt;", "");
	newStr = String(newStr).replace("<p-->", "<p>");
	return newStr;
}

function sendToActionScript(value) {
	//console.log("2014-02-10 2 sendToActionScript value :: ", value);
	var thisMv = thisMovie("wrapperContent1");
	//console.log("2014-02-10 2 thisMv :: ", thisMv);
	if (thisMv) {
		thisMv.sendToActionScript(value);
	}

}

function thisMovie(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		//console.log("2014-02-10 2 window[movieName] :: ", window[movieName]);
		return window[movieName];
	} else {
		//console.log("2014-02-10 2 document[movieName] :: ", document[movieName]);
		return document[movieName];
	}
}